package com.autoscript.ext.xmldata.database;

import java.awt.BorderLayout;
import java.awt.FileDialog;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;

import javax.swing.DefaultComboBoxModel;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.ListModel;
import javax.swing.SwingConstants;
import javax.swing.border.EmptyBorder;

import com.autoscript.ext.ISystemConstant;
import com.autoscript.ext.xmldata.database.config.DBConfigProxy;
import com.autoscript.ext.xmldata.database.model.datasource.DataSourceItemModel;
import com.autoscript.ext.xmldata.database.model.datasource.IDataSourceItemModel;
import com.autoscript.ext.xmldata.database.model.datasource.IDataSourceModel;
import com.autoscript.ext.xmldata.filter.CustFileNameFilter;
import com.autoscript.ui.helper.StringHelper;

public class DataSourceConfigDialog extends JDialog {

	/**
	 * 
	 */
	private static final long serialVersionUID = 3818188866106915211L;
	private final JPanel contentPanel = new JPanel();
	private JTextField textField_DriverClass;
	private JTextField textField_URL;
	private JTextField textField_user;
	private JPasswordField passwordField;
	private JTextField textField_DataSource;
	private IDataSourceItemModel dataSourceItemModel;
	private JList jarlist;
	private JComboBox comboBox_DBType;

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		try {
			DataSourceConfigDialog dialog = new DataSourceConfigDialog(null,null,"数据源配置",true);
			dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
			dialog.setVisible(true);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * Create the dialog.
	 */
	public DataSourceConfigDialog(IDataSourceItemModel dataSourceItemModel,Frame frame, String title, boolean modal) {
		super(frame,title,modal);
		this.dataSourceItemModel = dataSourceItemModel;
		setBounds(100, 100, 489, 343);
		getContentPane().setLayout(new BorderLayout());
		contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
		getContentPane().add(contentPanel, BorderLayout.CENTER);
		contentPanel.setLayout(new BorderLayout(0, 0));
		{
			JScrollPane scrollPane = new JScrollPane();
			contentPanel.add(scrollPane, BorderLayout.CENTER);
			{
				jarlist = new JList(new DefaultListModel());
				scrollPane.getViewport().setView(jarlist);

			}
		}
		{
			JPanel panel = new JPanel();
			contentPanel.add(panel, BorderLayout.EAST);
			panel.setLayout(new GridLayout(4, 1, 0, 0));
			{
				JButton addButton = new JButton("新增");
				addButton.addActionListener(new ActionListener() {
					public void actionPerformed(ActionEvent e) {
						FileDialog dlg;
						dlg = new FileDialog(DataSourceConfigDialog.this,"Jar文件",FileDialog.LOAD);
						dlg.setFilenameFilter(new CustFileNameFilter(".jar"));
						dlg.setVisible(true);
						String fileName;
						fileName = dlg.getDirectory()+dlg.getFile();
						if(!StringHelper.isEmpty(dlg.getFile()) && fileName.endsWith(".jar")){
							if(!isExistJarFile(fileName)){
								addJarFileToList(fileName);
							}
						}						
					}
				});
				panel.add(addButton);
			}
			{
				JButton delButton = new JButton("删除");
				delButton.addActionListener(new ActionListener() {

					@Override
					public void actionPerformed(ActionEvent e) {
						int selIndexs[] = jarlist.getSelectedIndices();
						if(selIndexs!=null && selIndexs.length>0){
							if(JOptionPane.showConfirmDialog(DataSourceConfigDialog.this, "是否移去该jar?", "移去jarFile", JOptionPane.YES_NO_OPTION)== JOptionPane.YES_OPTION){
								removeJarFileByIndexs(selIndexs);
							}
						}
					}
					
				});
				panel.add(delButton);
			}
			{
				JButton upbutton = new JButton("上移");
				upbutton.addActionListener(new ActionListener() {

					@Override
					public void actionPerformed(ActionEvent e) {
						int selIndexs[] = jarlist.getSelectedIndices();
						if(selIndexs!=null && selIndexs.length>0){
							if(selIndexs.length>1){
								JOptionPane.showMessageDialog(DataSourceConfigDialog.this, "只能选择一项!");
								return;
							}
							//如果是最顶项，就不移动了
							if(selIndexs[0]>0){
								swapJarList(selIndexs[0],selIndexs[0]-1);
							}
						}
					}
					
				});				
				panel.add(upbutton);
			}
			{
				JButton downButton = new JButton("下移");
				downButton.addActionListener(new ActionListener() {

					@Override
					public void actionPerformed(ActionEvent e) {
						int selIndexs[] = jarlist.getSelectedIndices();
						if(selIndexs!=null && selIndexs.length>0){
							if(selIndexs.length>1){
								JOptionPane.showMessageDialog(DataSourceConfigDialog.this, "只能选择一项!");
								return;
							}
							//如果是最底项，就不移动了
							if(selIndexs[0]<jarlist.getModel().getSize()-1){
								swapJarList(selIndexs[0],selIndexs[0]+1);
							}
						}
					}
					
				});				
				panel.add(downButton);
			}
		}
		{
			JPanel panel = new JPanel();
			FlowLayout flowLayout = (FlowLayout) panel.getLayout();
			flowLayout.setAlignment(FlowLayout.LEFT);
			contentPanel.add(panel, BorderLayout.NORTH);
			{
				JLabel lblNewLabel = new JLabel("驱动文件列表:");
				lblNewLabel.setHorizontalAlignment(SwingConstants.LEFT);
				panel.add(lblNewLabel);
			}
		}

		{
			JPanel buttonPane = new JPanel();
			buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT));
			getContentPane().add(buttonPane, BorderLayout.SOUTH);
			{
				JButton okButton = new JButton("确定");
				okButton.addActionListener(new ActionListener() {
					public void actionPerformed(ActionEvent e) {
						try{
						saveDataSource();
						}catch(Exception e1){
							e1.printStackTrace();
							JOptionPane.showMessageDialog(DataSourceConfigDialog.this, e1.getMessage());
							//恢复配置
							 DBConfigProxy.getInstance().resetDataSourceConfig();
							return;
						}
						DataSourceConfigDialog.this.dispose();
					}
				});
				okButton.setActionCommand("OK");
				buttonPane.add(okButton);
				getRootPane().setDefaultButton(okButton);
			}
			{
				JButton cancelButton = new JButton("取消");
				cancelButton.addActionListener(new ActionListener() {
					public void actionPerformed(ActionEvent e) {
						DataSourceConfigDialog.this.dispose();
					}
				});
				cancelButton.setActionCommand("Cancel");
				buttonPane.add(cancelButton);
			}
		}
		{
			JPanel panel = new JPanel();
			getContentPane().add(panel, BorderLayout.NORTH);
			GridBagLayout gbl_panel = new GridBagLayout();
			gbl_panel.columnWidths = new int[]{66, 367, 0};
			gbl_panel.rowHeights = new int[]{23, 0, 0, 0, 0, 0, 0};
			gbl_panel.columnWeights = new double[]{1.0, 1.0, Double.MIN_VALUE};
			gbl_panel.rowWeights = new double[]{0.0, 0.0, 0.0, 0.0, 0.0, 1.0, Double.MIN_VALUE};
			panel.setLayout(gbl_panel);
			{
				JLabel label = new JLabel("数据源：");
				label.setHorizontalAlignment(SwingConstants.LEFT);
				GridBagConstraints gbc_label = new GridBagConstraints();
				gbc_label.anchor = GridBagConstraints.EAST;
				gbc_label.insets = new Insets(0, 0, 5, 5);
				gbc_label.gridx = 0;
				gbc_label.gridy = 0;
				panel.add(label, gbc_label);
			}
			{
				textField_DataSource = new JTextField();
				GridBagConstraints gbc_textField_DataSource = new GridBagConstraints();
				gbc_textField_DataSource.insets = new Insets(0, 0, 5, 0);
				gbc_textField_DataSource.fill = GridBagConstraints.HORIZONTAL;
				gbc_textField_DataSource.gridx = 1;
				gbc_textField_DataSource.gridy = 0;
				panel.add(textField_DataSource, gbc_textField_DataSource);
				textField_DataSource.setColumns(10);
			}
			{
				JLabel label = new JLabel("驱动类名：");
				GridBagConstraints gbc_label = new GridBagConstraints();
				gbc_label.anchor = GridBagConstraints.EAST;
				gbc_label.insets = new Insets(0, 0, 5, 5);
				gbc_label.gridx = 0;
				gbc_label.gridy = 1;
				panel.add(label, gbc_label);
			}
			{
				textField_DriverClass = new JTextField();
				textField_DriverClass.setColumns(10);
				GridBagConstraints gbc_textField_DriverClass = new GridBagConstraints();
				gbc_textField_DriverClass.fill = GridBagConstraints.HORIZONTAL;
				gbc_textField_DriverClass.insets = new Insets(0, 0, 5, 0);
				gbc_textField_DriverClass.gridx = 1;
				gbc_textField_DriverClass.gridy = 1;
				panel.add(textField_DriverClass, gbc_textField_DriverClass);
			}
			{
				JLabel label = new JLabel("数据库URL:");
				GridBagConstraints gbc_label = new GridBagConstraints();
				gbc_label.anchor = GridBagConstraints.EAST;
				gbc_label.insets = new Insets(0, 0, 5, 5);
				gbc_label.gridx = 0;
				gbc_label.gridy = 2;
				panel.add(label, gbc_label);
			}
			{
				textField_URL = new JTextField();
				textField_URL.setColumns(10);
				GridBagConstraints gbc_textField_URL = new GridBagConstraints();
				gbc_textField_URL.fill = GridBagConstraints.HORIZONTAL;
				gbc_textField_URL.insets = new Insets(0, 0, 5, 0);
				gbc_textField_URL.gridx = 1;
				gbc_textField_URL.gridy = 2;
				panel.add(textField_URL, gbc_textField_URL);
			}
			{
				JLabel label = new JLabel("用户名：");
				GridBagConstraints gbc_label = new GridBagConstraints();
				gbc_label.anchor = GridBagConstraints.EAST;
				gbc_label.insets = new Insets(0, 0, 5, 5);
				gbc_label.gridx = 0;
				gbc_label.gridy = 3;
				panel.add(label, gbc_label);
			}
			{
				textField_user = new JTextField();
				textField_user.setColumns(10);
				GridBagConstraints gbc_textField_user = new GridBagConstraints();
				gbc_textField_user.fill = GridBagConstraints.HORIZONTAL;
				gbc_textField_user.insets = new Insets(0, 0, 5, 0);
				gbc_textField_user.gridx = 1;
				gbc_textField_user.gridy = 3;
				panel.add(textField_user, gbc_textField_user);
			}
			{
				JLabel label = new JLabel("密码：");
				GridBagConstraints gbc_label = new GridBagConstraints();
				gbc_label.anchor = GridBagConstraints.EAST;
				gbc_label.insets = new Insets(0, 0, 5, 5);
				gbc_label.gridx = 0;
				gbc_label.gridy = 4;
				panel.add(label, gbc_label);
			}
			{
				passwordField = new JPasswordField();
				GridBagConstraints gbc_passwordField = new GridBagConstraints();
				gbc_passwordField.fill = GridBagConstraints.HORIZONTAL;
				gbc_passwordField.insets = new Insets(0, 0, 5, 0);
				gbc_passwordField.gridx = 1;
				gbc_passwordField.gridy = 4;
				panel.add(passwordField, gbc_passwordField);
			}
			{
				JLabel lblNewLabel_1 = new JLabel("数据库类型:");
				GridBagConstraints gbc_lblNewLabel_1 = new GridBagConstraints();
				gbc_lblNewLabel_1.anchor = GridBagConstraints.EAST;
				gbc_lblNewLabel_1.insets = new Insets(0, 0, 0, 5);
				gbc_lblNewLabel_1.gridx = 0;
				gbc_lblNewLabel_1.gridy = 5;
				panel.add(lblNewLabel_1, gbc_lblNewLabel_1);
			}
			{
				comboBox_DBType = new JComboBox();
				GridBagConstraints gbc_comboBox_DBType = new GridBagConstraints();
				gbc_comboBox_DBType.fill = GridBagConstraints.HORIZONTAL;
				gbc_comboBox_DBType.gridx = 1;
				gbc_comboBox_DBType.gridy = 5;
				comboBox_DBType.setModel(new DefaultComboBoxModel());
				fillDBTypeComboBox();
				panel.add(comboBox_DBType, gbc_comboBox_DBType);
			}
		}
		dispDataSourceInfo(dataSourceItemModel);
	}
	/**
	 * 填充数据库类型组合框
	 */
	private void fillDBTypeComboBox() {
		DefaultComboBoxModel model= (DefaultComboBoxModel) comboBox_DBType.getModel();
		model.addElement(ISystemConstant.DBTYPE_ORACE);
		model.addElement(ISystemConstant.DBTYPE_MYSQL);
	}

	/**
	 * 保存数据源信息
	 * @throws Exception 
	 */
	protected void saveDataSource() throws Exception {
		IDataSourceModel dsModel = DBConfigProxy.getInstance().readDataSourceConfig();
		if(dataSourceItemModel==null){
			dataSourceItemModel = new DataSourceItemModel();
			dsModel.getDataSourceItems().add(dataSourceItemModel);
		}
		//填写各个属性
		dataSourceItemModel.setDriverClass(textField_DriverClass.getText());
		dataSourceItemModel.setJarFiles(getJarFiles());
		dataSourceItemModel.setName(textField_DataSource.getText());
		dataSourceItemModel.setPassword(String.valueOf(passwordField.getPassword()));
		dataSourceItemModel.setURL(textField_URL.getText());
		dataSourceItemModel.setUser(textField_user.getText());		
		dataSourceItemModel.setDBType(getSelectDBType());
		dataSourceItemModel.verify();
		//整个数据源模型验证
		dsModel.verify();
		//验证通过保存
		DBConfigProxy.getInstance().saveDataSourceConfig();
	}
	/**
	 * 获取选择的数据库类型
	 * @return
	 */
	private String getSelectDBType() {
		int selIndex = comboBox_DBType.getSelectedIndex();
		if(selIndex>=0){
			DefaultComboBoxModel model = (DefaultComboBoxModel) comboBox_DBType.getModel();
			return (String) model.getElementAt(selIndex);
		}else{
			return "";
		}
	}

	/**
	 * 从jar文件列表获取文件列表
	 * @return
	 */
	private List<String> getJarFiles() {
		ListModel listModel =  jarlist.getModel();
		List<String> jarFiles = new ArrayList<String>();
		for(int i=0;i<listModel.getSize();i++){
			jarFiles.add((String)listModel.getElementAt(i));
		}
		return jarFiles;
	}

	/**
	 * 交换文件列表 两个索引
	 * @param index1
	 * @param index2
	 */
	protected void swapJarList(int index1, int index2) {
		DefaultListModel listModel = (DefaultListModel) jarlist.getModel();
		String index1Val;
		index1Val = (String) listModel.getElementAt(index1);
		listModel.setElementAt((String)listModel.getElementAt(index2),index1);
		listModel.setElementAt(index1Val, index2);
	}

	/**
	 * 根据索引数组从jar文件列表中删除
	 * @param selIndexs
	 */
	protected void removeJarFileByIndexs(int[] selIndexs) {
		DefaultListModel listModel = (DefaultListModel) jarlist.getModel();
		for(int i=selIndexs.length-1;i>=0;i--){
			listModel.removeElementAt(selIndexs[i]);
		}
	}

	/**
	 * 增加文件名到jar列表框
	 * @param fileName
	 */
	protected void addJarFileToList(String fileName) {
		DefaultListModel listModel = (DefaultListModel) jarlist.getModel();
		listModel.addElement(fileName);
		
	}
	/**
	 * 判断jar文件在列表中是否存在
	 * @param fileName jar文件名
	 * @return
	 */
	protected boolean isExistJarFile(String fileName) {
		ListModel listModel = jarlist.getModel();
		String jarFileName;
		for(int i=0;i<listModel.getSize();i++){
			jarFileName = (String) listModel.getElementAt(i);
			if(jarFileName.equals(fileName)){
				return true;
			}
		}
		return false;
	}

	/**
	 * 显示数据源信息
	 * @param itemModel
	 */
	private void dispDataSourceInfo(IDataSourceItemModel itemModel) {
		if(itemModel!=null){
			textField_DataSource.setText(itemModel.getName());
			textField_DriverClass.setText(itemModel.getDriverClass());
			textField_URL.setText(itemModel.getURL());
			textField_user.setText(itemModel.getUser());
			passwordField.setText(itemModel.getPassword());		
			DefaultListModel listModel = (DefaultListModel) jarlist.getModel();
			listModel.clear();
			if(itemModel.getJarFiles()!=null){
				for(String fileName:itemModel.getJarFiles()){
					listModel.addElement(fileName);
				}
			}
			//选择数据库类型
			selectDBType(itemModel);
		}
	}
	/**
	 * 选中指定的
	 * @param itemModel
	 */
	private void selectDBType(IDataSourceItemModel itemModel) {
		DefaultComboBoxModel model = (DefaultComboBoxModel) comboBox_DBType.getModel();
		for(int i=0;i<model.getSize();i++){
			if(itemModel.getDBType().equals(model.getElementAt(i))){
				comboBox_DBType.setSelectedIndex(i);
				return;
			}
		}
	}

	public IDataSourceItemModel getDataSourceItemModel() {
		return dataSourceItemModel;
	}

	public void setDataSourceItemModel(IDataSourceItemModel dataSourceItemModel) {
		this.dataSourceItemModel = dataSourceItemModel;
	}

}
